"use client"
import React, { useEffect, useState } from "react";
import { Button, Input, Form, Space, List, Select, Card, Switch } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import styles from './index.module.css'
import baseInformationClass from "@/components/properties-panel-extension/components/index.module.css";
import { generateUniqueId } from "@/utils/Z";


interface MyComponentProps {
    bpmnInstance: any;
}

// 定义事件数据的类型，明确索引签名
interface EventData {
    messages: Array<{ name: string, id: string }>;
    errors: Array<{ name: string, id: string }>;
    signals: Array<{ name: string, id: string }>;
    upgrades: Array<{ name: string, id: string }>;
    [key: string]: Array<{ name: string, id: string }>; // 允许字符串索引
}

interface EventConfig {
    label: string;
    value: string;
    option: any;
}

// 事件配置组件
const EventConfigurationView: React.FC<MyComponentProps> = (props: any) => {
    const { bpmnInstance } = props
    const { modeling, modeler, moddle, bpmnElement = {}, elementRegistry, bpmnFactory } = bpmnInstance
    const [baseInfo, setBaseInfo] = useState<any>();

    const [eventData, setEventData] = useState<EventData>({
        messages: [],
        errors: [],
        signals: [],
        upgrades: []
    });
    const [eventType, setEventType] = useState<string>('');
    useEffect(() => {

        if (bpmnElement.businessObject) {
            setBaseInfo({
                ...bpmnElement.businessObject,
            })
            const definition = bpmnElement.businessObject.eventDefinitions || []
            console.log("bpmnElement.businessObject", definition);
            definition.forEach((item: any): any => {
                if (item.$type === 'bpmn:MessageEventDefinition') {
                    setEventType('message');
                } else if (item.$type === 'bpmn:SignalEventDefinition') {
                    setEventType('signal');
                } else if (item.$type === 'bpmn:ErrorEventDefinition') {
                    setEventType('error');
                } else if (item.$type === 'bpmn:TimerEventDefinition') {
                    setEventType('timer');
                } else if (item.$type === 'bpmn:EscalationEventDefinition') {
                    setEventType('escalation');
                }
            })
            updateEventData();
        }


    }, [bpmnElement.businessObject]);
    const updateEventData = () => {
        const definitions = modeler.getDefinitions();
        if (definitions?.rootElements) {
            setEventData({
                messages: definitions.rootElements.filter((el: any) => el.$type === 'bpmn:Message'),
                errors: definitions.rootElements.filter((el: any) => el.$type === 'bpmn:Error'),
                signals: definitions.rootElements.filter((el: any) => el.$type === 'bpmn:Signal'),
                upgrades: definitions.rootElements.filter((el: any) => el.$type === 'bpmn:Escalation')
            });
        }
    };


    // 示例：更新 eventConfig 的方法
    const updateEventConfig = (newConfig: Partial<EventConfig>) => {
        console.log(newConfig, 'newConfig')
        const eventDefinitions = bpmnElement.businessObject.eventDefinitions || [];
        console.log(eventDefinitions, 'eventDefinitions')
        eventDefinitions.forEach((item: any, index: number) => {
            if (item.$type === "bpmn:MessageEventDefinition") { // 假设我们只更新第一个 eventDefinition
                item.messageRef = eventData.messages.find(msg => msg.id === newConfig.value) || null;
            } else if (item.$type === "bpmn:SignalEventDefinition") { // 假设我们只更新第一个 eventDefinition
                item.signalRef = eventData.signals.find(sig => sig.id === newConfig.value) || null;
            } else if (item.$type === "bpmn:ErrorEventDefinition") { // 假设我们只更新第一个 eventDefinition
                item.errorRef = eventData.errors.find(err => err.id === newConfig.value) || null;
            } else if (item.$type === "bpmn:EscalationEventDefinition") { // 假设我们只更新第一个 eventDefinition
                item.escalationRef = eventData.upgrades.find(upg => upg.id === newConfig.value) || null;
            }
        })
        console.log(eventDefinitions, 'eventDefinitions')
        modeling.updateProperties(bpmnElement, {
            eventDefinitions: eventDefinitions
        });
    };



    return (
        <div className={baseInformationClass.listenerContainer}>

            <Form>
                {eventType !== 'timer' && (<Form.Item
                    label="选择事件"
                    labelCol={{ span: 6 }}
                    wrapperCol={{ span: 18 }}>
                    <Select
                        style={{ width: '80%' }}
                        options={eventData[eventType + 's']?.map((item: any) => ({
                            label: item.name,
                            value: item.id
                        })) || []}
                        value={bpmnElement.businessObject.eventDefinitions?.[0]?.[eventType + 'Ref']?.id}
                        onChange={(value, option) => {
                            updateEventConfig({ value, option });
                        }}
                        placeholder={`请选择`}
                    />
                </Form.Item>)}


            </Form>

        </div>
    );
};

export default EventConfigurationView;
